<?php

require_once(dirname(__DIR__) . '/api/DB.php');
require_once(dirname(__DIR__) . '/api/response.php');

$message = '';

try {

    $db = new DB();
    $pdo = $db::$pdo;

    // 查询文章
    $sql = 'select SQL_CALC_FOUND_ROWS * from articles';
    $page = isset($_GET['page']) ? $_GET['page'] : 1;
    $pageSize = isset($_GET['pageSize']) ? $_GET['pageSize'] : 10;
    $offset = ( $page - 1 ) * $pageSize;
    $params = [];
    $whereArr= [];

    if (isset($_GET['user_id']) && !empty($_GET['user_id'])) {
        $whereArr[] = 'user_id = ?';
        $params[] = $_GET['user_id'];
    }

    if (isset($_GET['title']) && !empty($_GET['title'])) {
        $whereArr[] = 'title like ?';
        $params[] = "%{$_GET['title']}%";
    };

    if (isset($_GET['category_id']) && !empty($_GET['category_id'])) {
        $whereArr[] = 'category_id = ?';
        $params[] = $_GET['category_id'];
    };

    if (!empty($whereArr)) {
        $sql .= ' where ' . implode(' and ', $whereArr);
    }

    // 添加排序
    $sql .= " order by update_at desc";

    // 添加分页
    $sql .= " limit {$offset},{$pageSize}";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $res = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 获取总条数
    $totalStmt = $pdo->query('select found_rows()');
    $total = $totalStmt->fetchColumn();

    // 添加总评论数
    $sql = 'select * from comments where article_id = ?';
    $stmt = $pdo->prepare($sql);
    foreach ($res as &$value) {
        $stmt->execute([$value['id']]);
        $value['comment_total'] = $stmt->rowCount();
        unset($value);
    }

    myResponse('', 1, 200, $res, $total);
} catch (Exception $e) {
    $message = $e->getMessage();
    myResponse($message, 0, 200);
}

